<template>
    <div class="root">
        <img src="../assets/opened_capsual.png" class="image" alt="">
        <div class="share-wrapper">
            <div class="share-icon">
                <svg class="icon" aria-hidden="true" @click="toShowSheet" style="color:white;width:24px;height:24px;marginRight: 32px;marginTop: 36px;">
                    <use xlink:href="#icon-bianjisekuai"></use>
                </svg>
                <svg class="icon" aria-hidden="true" @click="showShare = true" style="color:white;width:24px;height:24px;marginRight: 32px;marginTop: 36px;">
                    <use xlink:href="#icon-fenxiang"></use>
                </svg>
            </div>
        </div>
        <div class="activity-wrapper">
            <div class="cross-wrapper">
                <div class="cross-icon">
                    <van-icon @click="returnLast" name="close" size="20" color="#E4E4E4"/>
                </div>
            </div>
            <div class="title-wrapper">
                <div class="activity-title">
                    <span>{{ poolTitle }}</span>
                </div>
            </div>
            <div class="time-wrapper">
                <div class="activity-time">
                    <span>{{ startTime }} - {{ endTime }}</span>
                </div>
            </div>
            <div class="content-wrapper">
                <div class="activity-content">{{ poolContent }}</div>
            </div>
            <div class="floor-wrapper">
                <div class="floor-info" v-for="f in floorItemList" :style="isCreated && f.uid === GlobalData.uid ? myFloorStyle : otherFloorStyle">
                    <div class="floor-top">
                        <div class="floor-number">{{isCreated && f.uid === GlobalData.uid  ? '我' : `${f.idx}楼`}}</div>
                        <div class="partition">|</div>
                        <div class="floor-content">{{f.content}}</div>
                    </div>
                    <div class="floor-icon">
                        <div class="left-part">
                            <svg class="icon" aria-hidden="true" style="width:19px;height:19px;">
                                <use v-bind:xlink:href="f.mood"></use>
                            </svg>
                        </div>
                        <div class="right-part">
                            <div class="delete-icon" v-show="role === 'admin' && (!isCreated || f.uid !== GlobalData.uid)" @click="deleteCap(f.id)">
                                <van-icon name="delete-o" color="#A6A6A6" size="19"/>
                            </div>
                            <div class="report-icon" @click="reportCap(f.id)" v-show="!isCreated || f.uid !== GlobalData.uid">
                                <van-icon name="warning-o" color="#A6A6A6" size="19"/>
                            </div>
                            <div class="counter" v-show="!isCreated || f.uid !== GlobalData.uid">
                                <span>{{ f.likeNumber }}</span>
                            </div>
                            <div class="goodjob-icon" v-show="!isCreated || f.uid !== GlobalData.uid">
                                <van-icon name="good-job-o" :color="likeColor" size="19" v-show="!f.liked" @click="handleGiveLike(1, f.id, f.idx, f.liked)"/>
                                <van-icon name="good-job" color="#5ccdc8" size="19" v-show="f.liked" @click="handleGiveLike(0, f.id, f.idx, f.liked)"/>
                            </div>
                            <div class="modify-icon" v-show="isCreated && f.uid === GlobalData.uid" @click="handleModify(f.content, String(f.mood), f.id)">
                                <svg class="icon" aria-hidden="true" style="width:19px;height:19px;">
                                    <use xlink:href="#icon-tianxie"></use>
                                </svg>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <van-dialog v-model:show="showReportDialog" title="举报此发言" show-cancel-button confirm-button-text="确认" @confirm="confirmReport" :before-close="beforeCloseReport" closeOnClickOverlay>
        <van-form>
            <van-field
                v-model="reportInfo.reason"
                label="举报原因"
                placeholder="请填写举报原因"
                required
                :rules="[{ required: true, message: '举报原因不可为空' }]"
                clearable
                label-width="5em"
            />
        </van-form>
    </van-dialog>
    <van-share-sheet
        v-model:show="showShare"
        title="立即分享给好友"
        :options="shareOptions"
        @select="onSelect"
    />
    <van-action-sheet :title="isCreated ? '修改公共胶囊' : '添加公共胶囊'" v-model:show="showSheet">
        <div class="sheet">
            <div class="capsual-content">
                <div class="text-content">
                    <span>胶囊内容</span>
                </div>
                <div class="input-capsual-content">
                    <van-field v-model="newPublicCapsule.content" rows="3" autosize type="textarea" maxlength="200" placeholder="点击输入胶囊内容" show-word-limit style="backgroundColor: #fdfaf6;borderRadius: 10px;"/>
                </div>
            </div>
            <div class="capsual-mood">
                <div class="text-content">
                    <span>心情状态</span>
                </div>
                <div class="input-capsual-mood">
                    <van-field v-model="publicCapsuleMoodString" placeholder="选择心情状态" is-link readonly @click="showPicker=true" style="backgroundColor: #fdfaf6;"/>
                </div>
            </div>
            <div class="partition-line"></div>
            <div class="ok-btn-wrapper" @click="showDia">
                <div class="ok-btn">
                    <span>完成</span>
                </div>
            </div>
        </div>
    </van-action-sheet>
    <van-dialog v-model:show="showPicker" title="选择心情状态" show-cancel-button @confirm="confirmSelect" @cancel="nowSelect = 0" :before-close="beforeCloseSelect">
        <div class="mood-select-wrapper" v-show="showPicker">
            <div id="mood-22" class="mood" @click="nowSelect = 22;numberHashMood[nowSelect] = '微笑'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing22"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>微笑</span>
                </div>
            </div>
            <div id="mood-24" class="mood" @click="nowSelect = 24;numberHashMood[nowSelect] = '开心'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing24"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>开心</span>
                </div>
            </div>
            <div id="mood-27" class="mood" @click="nowSelect = 27;numberHashMood[nowSelect] = '眨眼'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing27"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>眨眼</span>
                </div>
            </div>
            <div id="mood-29" class="mood" @click="nowSelect = 29;numberHashMood[nowSelect] = '兴奋'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing29"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>兴奋</span>
                </div>
            </div>
            <div id="mood-18" class="mood" @click="nowSelect = 18;numberHashMood[nowSelect] = '思考'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing18"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>思考</span>
                </div>
            </div>
            <div id="mood-26" class="mood" @click="nowSelect = 26;numberHashMood[nowSelect] = '倒笑'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing26"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>倒笑</span>
                </div>
            </div>
            <div id="mood-11" class="mood" @click="nowSelect = 11;numberHashMood[nowSelect] = '哭泣'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing11"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>哭泣</span>
                </div>
            </div>
            <div id="mood-30" class="mood" @click="nowSelect = 30;numberHashMood[nowSelect] = '撇嘴'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing30"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>撇嘴</span>
                </div>
            </div>
            <div id="mood-31" class="mood" @click="nowSelect = 31;numberHashMood[nowSelect] = '难过'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing31"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>难过</span>
                </div>
            </div>
            <div id="mood-14" class="mood" @click="nowSelect = 14;numberHashMood[nowSelect] = '生气'">
                <div class="mood-icon">
                    <svg class="icon" aria-hidden="true" style="width: 25px;height: 25px;marginLeft:7px;">
                        <use xlink:href="#icon-a-biaoqing14"></use>
                    </svg>
                </div>
                <div class="icon-text">
                    <span>生气</span>
                </div>
            </div>
        </div>
    </van-dialog>
</template>

<script setup lang="ts">
import { ref,reactive,onMounted,watch } from 'vue';
import { useRouter,useRoute } from "vue-router";
import { getAllPublicCapsual,getOnePoolInfo,addPublicCapsual,giveLikePublicCapsual,reportPublicCapsual,deletePublicCapsual,alterPubliCapsual } from '../request/api';
import { useGlobalData } from '../store/index';
import { ElLoading } from 'element-plus';
import { Notify, Dialog } from 'vant';

interface PublicCapsual{
    poolId: string,
    pageSize: number,
    pageNum: number,
    order: string,   //1是正序，0是逆序
    type:string, //hot是按热度排序，time是按时间排序
}
interface ReportInfo{
    key: string,
    reason: string,
}
interface DeleteInfo {
    key: string,
}
interface Options {
    lock: boolean,
    text: string,
    background: string,
}
interface NewPublicCapsule {
    poolId: string,
    content: string,
    mood: number | undefined,
}
interface AlterPublicCapsule {
    id: string,
    mood?: number,
    content?: string,
}
interface FloorItem {
    idx?: number,
    content: string,
    createdAt: string,
    id: string,
    likeNumber: number,
    mood: number,
    poolId: string,
    uid: string,
    liked: boolean,
}
interface GiveLike {
    key: string,  /* 即被点赞的胶囊的id */
    action: "1"|"0", /* 1是点赞，2是取消点赞 */
}
const options: Options = {
    lock: true,
    text: "Loading...",
    background: 'rgba(0,0,0,0.7)'
}
const GlobalData = useGlobalData();
const router = useRouter();
const route = useRoute();
const shareOptions = [
    { name: '微信', icon: 'wechat' },
    { name: 'qq', icon: 'qq' },
    { name: '复制链接', icon: 'link' },
    { name: '分享海报', icon: 'poster' },
    { name: '二维码', icon: 'qrcode' },
];
var poolTitle = ref<string>("");
var poolContent = ref<string>("");
var poolState = ref<number>(0);
var startTime = ref<string>("");
var endTime = ref<string>("");
var likeColor = ref<string>("#A6A6A6");
var showReportDialog = ref<boolean>(false);
var role = ref<string>("");
var showShare = ref<boolean>(false);
var showSheet = ref<boolean>(false);
var showPicker = ref<boolean>(false);
var nowSelect = ref<number>(0);
var addOrAlter = ref<number>(1);  //1表示添加胶囊，2表示修改胶囊
var publicCapsuleMoodString = ref<string>("");
var isCapsuleLiked = ref<boolean[]>([]);  //判断一个胶囊是否被点赞过了
var isCreated = ref<boolean>(false);  //该用户是否已经创建过公共胶囊了
var reportInfo = reactive<ReportInfo>({
    key: "",
    reason: "",
});
var deleteInfo = reactive<DeleteInfo>({
    key: "",
})
var publicCapsual = reactive<PublicCapsual>({
    poolId: "",
    pageSize: 10,
    pageNum: 2,
    order: "1",
    type: "time",
});
var newPublicCapsule = reactive<NewPublicCapsule>({
    poolId: "",
    content: "",
    mood: undefined,
})
var alterPubliCapsule = reactive<AlterPublicCapsule>({
    id: "",
    mood: 0,
    content: "",
})
var giveLike = reactive<GiveLike>({
    key: "",
    action: "1",
})
var myFloorStyle = reactive<Object>({
    backgroundColor: '#dbf2f0'
})
var otherFloorStyle = reactive<Object>({
    backgroundColor: '#fdfaf6'
})
const objectHashMood = {
    "22": "微笑",
    "24": "开心",
    "27": "眨眼",
    "29": "兴奋",
    "18": "思考",
    "26": "倒笑",
    "11": "哭泣",
    "30": "撇嘴",
    "31": "难过",
    "14": "生气",
} 
const beforeClose = (action:string) => new Promise((resolve) => {
    //console.log(action);
    if (action == "confirm") {
        setTimeout(() => {
            resolve(true);
            if (isNull(newPublicCapsule.content) || !newPublicCapsule.mood) {
                Notify({
                    type: "warning",
                    message: "内容或心情不可为空",
                    duration: 1000,
                })
            } else if (addOrAlter.value === 1) {
                addPublicCapsual(newPublicCapsule).then((res:any) => {
                    console.log(res);
                    if (res && res.error_code == 0) {
                        Notify({
                            type: "success",
                            message: "添加成功",
                            duration: 1000,
                        })
                        showSheet.value = false;
                        reGetAllPublicCapsual();
                    }
                })
            } else if (addOrAlter.value === 2) {
                alterPubliCapsule.mood = nowSelect.value;
                alterPubliCapsule.content = newPublicCapsule.content;
                alterPubliCapsual(alterPubliCapsule).then((res:any) => {
                    console.log(res);
                    if (res && res.error_code == 0) {
                        Notify({
                            type: "success",
                            message: "修改成功",
                            duration: 1000,
                        })
                        showSheet.value = false;
                        reGetAllPublicCapsual();
                    }
                })
            }
        }, 1000);
    } else {
        resolve(true);
    }
})
const beforeCloseDel = (action:string) => new Promise((resolve) => {
    if (action == 'confirm') {
        setTimeout(() => {
            resolve(true);
            deletePublicCapsual(deleteInfo).then((res:any) => {
                console.log(res);
                if (res && res.error_code == 0) {
                    Notify({
                        type: 'success',
                        message: "删除成功",
                        duration: 1000,
                    })
                    reGetAllPublicCapsual();
                }
            })
        }, 1000);
    } else {
        resolve(true);
    }
})
var dialogInfo = reactive<Object>({
    title: '提示',
    message: '确认完成编辑吗？',
    beforeClose,
})
var delInfo = reactive<Object>({
    title: '提示',
    message: '确认要删除该公共胶囊吗？',
    beforeClose: beforeCloseDel,
})
var floorItemList = ref<FloorItem[]>([]);
let loading: any;
let numberHashMood : string[] = [];
const returnLast = () => {  //点叉号回到上一行
    router.go(-1);
}
const reportCap = (id:string) => {
    showReportDialog.value = true;
    reportInfo.key = id;
}
const deleteCap = (id:string) => {
    Dialog.confirm(delInfo);
    deleteInfo.key = id;
}
const handleGiveLike = (action:number, id:string, idx:number, liked:boolean) => { //1表示点赞，0表示取消点赞
    giveLike.action = String(action as 1|0) as "1"|"0";
    giveLike.key = id;
    console.log("action" + action);
    giveLikePublicCapsual(giveLike).then((res:any) => {
        console.log(res);
        if (res.error_code == 0) {
            if (action == 1 && !liked) { /* 是点赞但没有被点赞过 */
                floorItemList.value[idx-1].likeNumber++; /* 保证页面不刷新的情况下likeNumber虚假的变化 */
            } else if (action == 0 && liked) {
                floorItemList.value[idx-1].likeNumber--;
            }
            reGetAllPublicCapsual();
        } else if (!res) { /* res是undefined，表明已经点赞过了，不能重复点赞 */
            //pass
        }
    })
}
const onSelect = (option:any) => {  //分享面板选择函数

}
const confirmSelect = () => {
    console.log(nowSelect.value);
    if (nowSelect.value != 0) {
        publicCapsuleMoodString.value = numberHashMood[nowSelect.value];
        newPublicCapsule.mood = nowSelect.value;
    }
}
const confirmReport = () => {
    if (!isNull(reportInfo.reason)) {
        reportPublicCapsual(reportInfo).then((res:any) => {
            console.log(res);  
            if (res && res.error_code == 0) {
                Notify({
                    type: 'success',
                    message: "举报成功",
                    duration: 1000,
                })
            }
        })
    }
}
const toShowSheet = () => {
    if (isCreated.value) {
        Notify({
            type: 'warning',
            message: '您已经参与过该活动了',
            duration: 1000,
        })
    } else if (poolState.value === 4) {
        Notify({
            type: 'warning',
            message: '该活动已结束',
            duration: 1000,
        })
    } else {
        addOrAlter.value = 1;  //切换成添加状态
        showSheet.value = !showSheet.value;
    }
}
const handleModify = (content:string, mood:string, id:string) => {  //修改自己发过的楼层
    if (poolState.value === 4) {
        Notify({
            type: 'warning',
            message: '该活动已结束',
            duration: 1000,
        })
    } else {
        addOrAlter.value = 2;  //切换成修改状态
        alterPubliCapsule.id = id;
        newPublicCapsule.content = content;
        publicCapsuleMoodString.value = objectHashMood[Number(mood.slice(16))];
        showSheet.value = !showSheet.value;
    }
}
const isNull = (str:string) => {
    if(str == "") return true;
    let regu = "^[ ]+$";
    let re = new RegExp(regu);
    return re.test(str);
}
const showDia = () => {
    Dialog.confirm(dialogInfo);
}
const beforeCloseSelect = (action:string) : boolean => {
    if (action == 'confirm' && nowSelect.value == 0) {
        Notify({
            type: 'warning',
            message: '未选择心情状态',
            duration: 1000,
        })
        return false;
    }
    return true;
}
const beforeCloseReport = (action:string) : boolean => {
    if (action == 'confirm' && isNull(reportInfo.reason)) {
        Notify({
            type: 'warning',
            message: '举报原因不能为空',
            duration: 1000,
        })
        return false;
    }
    return true;
}
const reGetAllPublicCapsual = () => {
    let loading = ElLoading.service(options);
    getAllPublicCapsual(publicCapsual).then((res:any) => {
        console.log(res);
        floorItemList.value.length = 0;
        let len = res.result.length;
        isCreated.value = false;  /* 重置为没有创建过 */
        for(let i=0;i<len;i++) {
            if (res.result[i].uid === GlobalData.uid) isCreated.value = true;
            res.result[i].mood = "#icon-a-biaoqing" + res.result[i].mood;
            floorItemList.value.push({idx:i+1, ...res.result[i]});
        }
        loading.close();
    })
}
const onMounted_dup = () => {
    role.value = GlobalData.role;
    let poolId:string = String(route.query.poolId) as string;
    publicCapsual.poolId = poolId;
    newPublicCapsule.poolId = poolId;
    getOnePoolInfo({id:poolId}).then((res:any) => {
        console.log(res);
        poolTitle.value = res.result.title;
        poolContent.value = res.result.content;
        poolState.value = res.result.state;
        startTime.value = res.result.startTime.slice(0,10);
        endTime.value = res.result.endTime.slice(0,10);
    })
    let count:number = 0;   //楼层索引
    reGetAllPublicCapsual();
}
watch(()=>route.query.poolId,(newVal)=>{
    if(newVal && newVal != publicCapsual.poolId){
        loading = ElLoading.service(options);
        onMounted_dup();
        loading.close();
    }
})
onMounted(onMounted_dup);
</script>

<style lang="less" scoped>
    .root{
        height: 100%;
        background-color: #5ccdc8;
        .share-wrapper{
            display: flex;
            flex-direction: row-reverse;
            .share-icon{
                position: absolute;
            }
        }
        .image{
            position: absolute;
            z-index: 1;
            width: 200px;
        }
        .activity-wrapper{
            position: relative;
            display: flex;
            flex-direction: column;
            background: white;
            box-shadow: 2px 2px 10px rgb(211, 203, 203);
            width: 86%;
            height: 82%;
            top: 95px;
            left: 7%;
            margin: 0 0 32px 0;
            border-radius: 18px;
            .cross-wrapper{
                display: flex;
                flex-direction: row-reverse;
                margin-top: 8px;
                margin-right: 10px;
            }
            .title-wrapper{
                display: flex;
                justify-content: center;
                margin-top: 10px;
                .activity-title{
                    font-weight: 400;
                    font-size: 20px;
                }
            }
            .time-wrapper{
                display: flex;
                justify-content: center;
                margin-top: 4px;
                .activity-time{
                    font-weight: 400;
                    font-size: 14px;
                    color: #A6A6A6;
                }
            }
            .content-wrapper{
                display: flex;
                justify-content: center;
                margin: 4px 28px 0 28px;
                .activity-content{
                    font-weight: 400;
                    font-size: 12px;
                    color: #A6A6A6;
                    display: -webkit-box;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    -webkit-box-orient: vertical;
                    -webkit-line-clamp: 2;
                }
            }
            .floor-wrapper{
                display: flex;
                flex-direction: column;
                padding: 0 22px 0 22px;
                margin: 8px 0px 8px 0px;
                overflow: scroll;
                .floor-info{
                    margin-top: 6px;
                    display: flex;
                    flex-direction: column;
                    border-radius: 6px;
                    background-color: #FDFAF6;
                    padding: 8px 12px 8px 12px;
                    .floor-top{
                        display: flex;
                        .floor-number{
                            width: 10%;
                            color: #A6A6A6;
                            font-weight: 400;
                            font-size: 14px;
                        }
                        .partition{
                            widows: 5%;
                            margin-left: 4px;
                            margin-right: 4px;
                            color: #d4cece;
                            font-weight: 400;
                            font-size: 14px;             
                        }
                        .floor-content{
                            width: 85%;
                            font-weight: 400;
                            font-size: 12px;
                            color: #626262;
                            display: -webkit-box;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            -webkit-box-orient: vertical;
                            -webkit-line-clamp: 4;
                        }
                    }
                    .floor-icon{
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                        margin-top: 8px;
                        .right-part {
                            display: flex;
                            flex-direction: row-reverse;
                            .report-icon{
                                margin-right: 3px;
                            }
                            .goodjob-icon{
                                margin-right: 2px;
                            }
                            .counter{
                                margin-right: 10px;
                                color: #a6a6a6;
                                font-size: 13.5px;
                                align-self: center;
                            }
                        }
                    }
                }
            }
        }
    }
    .sheet {
        display: flex;
        flex-direction: column;
        .capsual-content {
            margin: 0 32px 0 32px;
            .text-content {
                font-size: 16px;
                font-weight: 400;
                margin-bottom: 10px;
                margin-left: 2px;
            }
            .input-capsual-content {
                margin-bottom: 20px;
            }
        }
        .capsual-mood {
            margin: 0 32px 0 32px;
            .text-content {
                font-size: 16px;
                font-weight: 400;
                margin-bottom: 10px;
                margin-left: 2px;
            }
            .input-capsual-mood {
                margin-bottom: 20px;
            }
        }
        .partition-line{
            background-color: #f7f8fa;
            height: 8px;
        }
        .ok-btn-wrapper{
            height: 48.8px;
            display: flex;
            justify-content: center;
            align-items: center;
            .ok-btn{
                font-size: 16px;
                font-weight: 400;
            }
        }
    }
    .mood-select-wrapper {
        display: flex;
        flex-direction: column;
        #mood-22 {
            border-top: 1px solid #968a8a;
        }
        :hover {
            transform: scale(1.1);
            background-color: #5ccdc8;
        }
        .mood {
            display: flex;
            justify-content: center;
            margin-top: 5px;
            border-bottom: 1px solid #968a8a;
            padding: 2px 0px;
            .mood-icon {
                margin-right: 15px;
            }
            .icon-text {
                margin-left: 15px;
                line-height: 25px;
            }
        }
    }
</style>